import {useRequest} from '@umijs/hooks';
import {Button, Cascader, DatePicker, Form, Input, message, Modal, Radio, Switch, Tooltip} from 'antd';
import moment from 'moment';
import {Store} from 'rc-field-form/lib/interface';
import React, {useState} from 'react';
import {useDispatch} from 'react-redux';
import {fetchRequest} from '../../../../../utils/Request';
import {url} from '../../../../../utils/url';
import '../../index.css';
import {getSecretString} from "../../../../../utils/encrypt";
import {QuestionCircleOutlined} from "@ant-design/icons";

const {RangePicker} = DatePicker

interface InfoState {
    whiteCard: boolean,
    face: boolean,
    blackCard: boolean,
    blackCardCode: string
}

interface ValidateState {
    state: "" | "success" | "warning" | "error" | "validating" | undefined,
    help: string | undefined,

}

// interface EntranceInfo {
//     studentName:string,
//     phone:string,
//     whiteCard:boolean,
//     face:boolean,
//     whiteCardCode:string,
//     certNum:string,
//     blackCardCode:string,
//     userTypeId:number,
//     startDate:datetime,
//     endDate:moment( value.graduationDate).format('YYYY-MM-DD'),
//     blaceCard:props.info.blackCard,
//     deptId:props.info.data[0].deptId,
//     collegeId:"118917293861",
//     collegeAreaId:"3",
//     building:"3",
//     unit:"2",
//     floor:"1",
//     room:"102"
// }

interface HealthRequestParams {
    idCard: string,
    phone: string,
    name: string
}

interface RequestAddres {
    "level": number,
    "collegeId": string,
    "collegeAreaId": string,
    "building": string,
    "unit": string,
    "floor": string
}

interface ValidateParams {
    cardCode: string,
    cardType: number
}

const type = {
    2: {text: "该人员的防疫核验为告警", color: "#fdec38"},
    3: {color: "#0ec671", text: "该人员的防疫核验为正常"},
    1: {color: "#f50206", text: "该人员的防疫核验为危险"},
    4: {color: undefined, text: "该人员的防疫核验为未知"},
    5: {color: undefined, text: "获取该人员的防疫核验失败"},
    6: {color: undefined}
}
export default function BasicInfoForm(props: any) {

    // console.log("新增门禁详细人员信息")
    // console.log(getSecretString(props.info.data[0].realCertNum))
    // console.log(props.info.data[0].realCertNum)
    const [form] = Form.useForm();
    const [state, setstate] = useState<InfoState>(typeof props.info.basicInformation === "undefined" ?
        {
            whiteCard: false, face: false, blackCard: props.info.isBlackCard,
            blackCardCode: typeof props.info.cardCode === "undefined" ? "" : props.info.cardCode
        } :
        typeof props.info.data[0].openType === "undefined" ?
            {
                whiteCard: false, face: false, blackCard: props.info.isBlackCard,
                blackCardCode: typeof props.info.cardCode === "undefined" ? "" : props.info.cardCode
            } :
            {
                ...props.info.data[0].openType, blackCard: props.info.isBlackCard,
                blackCardCode: props.info.cardCode,
                whiteCard: props.info.isBlackCard ? false : props.info.data[0].openType.whiteCard,
            })
    const formItemLayout = {
        labelCol: {
            xs: {span: 24},
            sm: {span: 8},
        },
        wrapperCol: {
            xs: {span: 24},
            sm: {span: 10},
        },
    };

    const [certType, setcertType] = useState([])


    const dispatch = useDispatch();

    const [addressNode, setAddressNode] = useState(props.info.addressNode)
    // console.log("addressNode")
    // console.log(addressNode)

    const loadData = (selectedOptions: any) => {

        const targetOption = selectedOptions[selectedOptions.length - 1];



        const isHavingDorm = form.getFieldValue('isHavingDorm')//是否有宿舍
        const level = targetOption?.['level']
        targetOption.loading = true;
        if (!isHavingDorm) {
            if (level == 1) {

                return
            }
        }


        //


        targetOption.loading = false;
        let jsondata: any = [];
        let addrArray: any = [];
        selectedOptions.forEach(function (item: any) {
            addrArray.push(item['value'])
        })

        getAllAdd({
            "level": targetOption['level'] + 1,
            "collegeId": typeof addrArray[0] === "undefined" ? "" : addrArray[0],
            "collegeAreaId": typeof addrArray[1] === "undefined" ? "" : addrArray[1],
            "building": typeof addrArray[2] === "undefined" ? "" : addrArray[2],
            "unit": typeof addrArray[3] === "undefined" ? "" : addrArray[3],
            "floor": typeof addrArray[4] === "undefined" ? "" : addrArray[4]

        }).then((e: any) => {


            jsondata = e
            if (!isHavingDorm) {
                if (level == 0) {
                    jsondata.map((item: any) => item.isLeaf = true)
                    console.log(jsondata)
                }
            }

            targetOption.loading = false;
            targetOption.children = jsondata;


            setAddressNode([...addressNode])
        })

    };

    function onFinish(value: Store) {
        // console.log(value)
        const data = [];

        if (value.whiteCard) {
            data.push("白卡开门")
        } else if (state.blackCard) {
            data.push("翼卡通开门")
        }

        if (value.face) {
            data.push("人脸开门")
        }

        if (value.isHavingDorm && value.allAddress.length != 6) {
            Modal.error({content: "宿舍地址请完整选择！"});
            return false;
        }

        if (!value.isHavingDorm && value.allAddress.length != 2) {
            Modal.error({content: "宿舍地址请完整选择！"});
            return false;
        }

        if (props.info.ifFaceNecessary && !value.face) {
            Modal.error({content: "该区域强制要求录入人脸!"});
            return;
        }

        if (data.length === 0) {
            Modal.error({content: "必须要选择一种开门方式!"});
            return;
        }
        submitAddEntrance.run(value);


    }

    async function getAllAdd(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                // console.log('getAllAdd:',json)
                return json.data
            } else {
                // console.log('getAllAdd:',json)
                return []
            }
        } catch (error: any) {
            // console.log('error:',error)
        }
    }

    const OnChange = (value: any, selectedOptions: any) => {
        console.log('selectedOptions', selectedOptions);

    };
    const [help, sethelp] = useState<undefined | string>(undefined)
    const {info} = props;

    //提交开门方式的接口
    async function submitAddEntranceRequest(value: any) {
        console.log("新增门禁卡")
        console.log(value)
        const params = {
            step: 2,
            studentName: props.info.data[0].studentName,
            phone: getSecretString(props.info.phone),
            whiteCard: typeof value.whiteCard === "undefined" ? "false" : String(value.whiteCard),
            face: typeof value.face === "undefined" ? "false" : String(value.face),
            whiteCardCode: typeof value.whiteCardCode === "undefined" ? "" : value.whiteCardCode,
            imei: typeof value.imeiCardCode === "undefined" ? "" : value.imeiCardCode,
            certNum: getSecretString(props.info.data[0].realCertNum),
            blackCardCode: props.info.blaceCardCode,
            userTypeId: 5,
            startDate: moment(value.startSchoolDate).format('YYYY-MM-DD'),
            endDate: moment(value.graduationDate).format('YYYY-MM-DD'),
            blackCard: String(props.info.isBlackCard),
            deptId: props.info.data[0].deptId,
            collegeId: value.allAddress[0],
            collegeAreaId: value.allAddress[1],
            building: value.allAddress[2],
            unit: value.allAddress[3],
            floor: value.allAddress[4],
            room: value.allAddress[5],
            isHavingDorm: value.isHavingDorm ? 1 : 0

        }
        console.log(params)

        if (value.whiteCard) {
            if (params.whiteCardCode === "" && params.imei === "") {
                Modal.error({content: "白卡卡号和IMEI卡号请至少输入一项！"});
                return false;
            }
        }

        try {
            const json = await fetchRequest(url.ADD_NEW_ENTRANCE, params);
            if (json.success) {
                props.onSubmit();
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const [value, setValue] = React.useState(0)
    //是否有宿舍修改
    const isHavingDormChange = async (e: any) => {
        setValue(e.target.value)
        form.setFieldsValue({
            allAddress:[]
        })

    }

    const submitAddEntrance = useRequest(submitAddEntranceRequest, {
        manual: true,
        loadingDelay: 200
    })

    function filter(inputValue: string, path: any[]) {
        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    return (
        <Form onFinish={onFinish} form={form} {...formItemLayout}
              initialValues={typeof props.info.data[0] === "undefined" ||
              props.info.data[0].length === 0 ? {whiteCard: false, face: false} : {
                  studentName: props.info.data[0].studentName,
                  startSchoolDate: moment(props.info.data[0].startSchoolDate),
                  graduationDate: moment(props.info.data[0].graduationDate),
                  credentialsNum: props.info.data[0].certNum,
                  isHavingDorm: props.info.data[0]?.isHavingDorm ?? 0
              }}>

            <Form.Item extra={help} label="姓名" name="studentName" rules={[{required: true}]}>
                <Input disabled={true}/>
            </Form.Item>

            <Form.Item label="是否有宿舍">
                <Form.Item
                    name="isHavingDorm"
                    noStyle
                >
                    <Radio.Group onChange={isHavingDormChange}>
                        <Radio value={0}>否</Radio>
                        <Radio value={1}>是</Radio>
                    </Radio.Group>

                </Form.Item>
            </Form.Item>

            <Form.Item className="form-control-item" name="allAddress" label="宿舍地址" rules={
                [{required: true, message: '必须选择宿舍地址'}]
            }>

                <Cascader
                    options={addressNode}
                    loadData={loadData}
                    onChange={OnChange}
                    showSearch={{filter}}
                    placeholder="请输入设备地址"
                    style={{width: 200}}
                    changeOnSelect
                />

            </Form.Item>

            <Form.Item validateTrigger="onBlur" label="身份证号" name="credentialsNum"
                       rules={[{required: true, message: "必须要填写证件号码!"}]}>
                <Input disabled={true}/>
            </Form.Item>

            <Form.Item extra={help} label="入学时间" name="startSchoolDate"
                       rules={[{required: true, message: "必须要选择门禁期限"}]}>
                <DatePicker/>
            </Form.Item>
            <Form.Item extra={help} label="毕业时间" name="graduationDate" rules={[{required: true, message: "必须要选择门禁期限"}]}>
                <DatePicker/>
            </Form.Item>

            <Form.Item
                // help={props.info.isBlackCard ? "该手机号为翼卡通,不能开通白卡开门!" : undefined}
                help={props.info.isBlackCard ? "该手机号为翼卡通" : undefined}
                label="白卡开门" name="whiteCard"
                // valuePropName="checked"
            >
                <Switch
                    // disabled={props.info.isBlackCard}
                    onChange={value => {
                        setstate({...state, whiteCard: value})
                    }}
                />
            </Form.Item>

            <Form.Item label="白卡卡号" name="whiteCardCode" style={state.whiteCard ? undefined : {display: 'none'}}>
                <Input/>
            </Form.Item>

            <Form.Item label="IMEI卡号" name="imeiCardCode" style={state.whiteCard ? undefined : {display: 'none'}}>
                <Input/>
            </Form.Item>

            <Form.Item help={info.ifFaceNecessary ? "要求必须要开通人脸开门" : undefined} label="开通人脸开门" name="face"
                       valuePropName="checked">
                <Switch onChange={value => {
                    setstate({...state, face: value})
                }} disabled={info.ifFaceNecessary && state.face}/>
            </Form.Item>

            <div style={{textAlign: 'center'}}>
                <Button onClick={props.onPrev} style={{marginRight: '8px'}}>上一步</Button>
                <Button htmlType="submit" type="primary" style={{marginRight: '8px'}}
                        loading={submitAddEntrance.loading}>提交</Button>
            </div>
        </Form>
    )

}
